package vip.wangwenhao.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import vip.wangwenhao.autoconfigure.constants.GatewayConstants;
import vip.wangwenhao.autoconfigure.constants.Oauth2Constants;

/**
 * @author wangwenhao
 */
@Component
public class TokenFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //token（用户身份）判断

        ServerHttpRequest request = exchange.getRequest();
        String accessToken = request.getQueryParams().getFirst("access_token");
        String authorization = request.getHeaders().getFirst("Authorization");
        ServerHttpRequest req = exchange.getRequest().mutate()
                .headers(httpHeaders -> {
                    httpHeaders.set(GatewayConstants.GATEWAY_AUTH_HEADER, GatewayConstants.FROM_SECRET);
                    if (!StringUtils.isEmpty(authorization)) {
                        httpHeaders.set("Authorization", authorization);
                    }
                    if (!StringUtils.isEmpty(accessToken)) {
                        httpHeaders.set("Authorization", Oauth2Constants.BEARER_AUTHENTICATION + accessToken);
                    }
                }).build();
        return chain.filter(exchange.mutate().request(req.mutate().build()).build());
    }
}